//
//  BLVideoPlayer.swift
//  BLVideoPlayer
//
//  Created by wkun on 2023/9/2.
//

import UIKit
import MobileVLCKit

open class BLVideoPlayer: UIViewController {
    
    let controlView = BLPlayerControlView()
    let nodataView = BLVideoPlayerNoDataView()
    let vlcView = UIView()
    
    let player = VLCMediaPlayer()
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupUI()
        
//        let tp = "smb://cgw:htc@192.168.1.103/cgw/Desktop/1yinyuehui/王杰/mv/4k修复王杰《回家》-威武神经-BV1SL411Q7wx-HaykPn6z1DGmEh8q/4k修复王杰《回家》-威武神经-BV1SL411Q7wx-HaykPn6z1DGmEh8q.mp4"
        
//        let td = YiFilePath.share.songDir
//        let tp = td.appendPath(pathname: "1.mp4")
//        let tp = "smb://wkun:1212@192.168.0.101/workspace1111/course/ff.mp4"
        
        let tp = "smb://cgw:htc@192.168.1.103/cgw/Desktop/ff.mp4"
//        self.play(withPath: tp)
        let url = URL.init(string: tp)!
        self.play(withURL: url)
    }
    
    open override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        self.stop()
    }
    
    deinit{
        self.stop()
    }
    
    // MARK: - 播放与暂停
    open func play(withURL url: URL, videoTitle: String? = nil) {
                
        self.stop()
        
        self.nodataView.isHidden = true
        self.controlView.titleL.text = videoTitle
        let media = VLCMedia(url: url)
        player.media = media
        player.play()
    }
    
    open func play(withPath path: String?) {
        
        guard let path = path else {
            return
        }
        
        //路径中有可能含有中文，所以编码一次
        guard let encodedUrlString = path.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
            return
        }
        
//        guard let url = URL(string: encodedUrlString) else {
//            return
//        }
        
        let url = NSURL.init(fileURLWithPath: encodedUrlString)
            
        self.play(withURL: url as URL, videoTitle: url.lastPathComponent)
    }
    
    open func stop() {
        self.player.stop()
    }
    
    // MARK: - 控制视图设置
    open func setEnableColumnAndBrightDrag(_ enable: Bool) {
        self.controlView.enableColumnAndBrightDrag = enable
    }
    
    // MARK: - 设置播放器
    func setupPlayer() {
        /*
        let manager = ZFAVPlayerManager()
        manager.shouldAutoPlay = true
        
        player.currentPlayerManager = manager
        player.disableGestureTypes = [.all]
        player.allowOrentitaionRotation = false
    
        self.player.controlView = self.controlView
        
        weak var ws = self
        player.playerPlayStateChanged = { asset, state in
            guard let btn = ws?.controlView.playBtn else {
                return
            }
            if state == .playStatePlaying {
                btn.isSelected = true
            }else{
                btn.isSelected = false
            }
            
            if state == .playStatePlaying {
                if ws?.controlView.bgView.isHidden == false {
                    DispatchQueue.main.asyncAfter(deadline: .now()+2.0) {
                        ws?.controlView.bgView.isHidden = true
                    }
                }
            }
        }
        
        player.playerDidToEnd = { asset in
            ws?.player.currentPlayerManager.replay()
        }
        
        player.playerPlayTimeChanged = { asset, time, duration in
            
            //若正在拖动进度，则忽略
            if ws?.controlView.dragType == .progress {
                return;
            }
            
            if let progress = ws?.player.progress {
                ws?.controlView.sliderView.value = progress
            }
            
            ws?.controlView.timeView.currTimeL.text = time.toHourMinSecond()
            ws?.controlView.timeView.totalTimeL.text = duration.toHourMinSecond()
        }
         */
    }
    
    // MARK: - SetupUI
    func setupUI() {
        self.view.backgroundColor = .black
        vlcView.bg("#000").embedIn(self.view)
        
        self.player.delegate = self
        self.player.drawable = self.vlcView
        
        self.controlView.player = self.player
        self.controlView.embedIn(self.view)
        
        self.nodataView.embedIn(self.view)
        self.nodataView.isHidden = true
        
        self.controlView.backBtn.onTap {
            self.dismiss(animated: true)
        }
    }
}

// VLC Player
extension BLVideoPlayer: VLCMediaPlayerDelegate{
    
    // MARK: - VLC Delegate
    public func mediaPlayerStateChanged(_ aNotification: Notification) {
        
//        print("state改变：\(player.state.rawValue)")
        
        self.controlView.playBtn.isSelected = (player.state == .playing || player.state == .buffering)
    }
    
    public func mediaPlayerTimeChanged(_ aNotification: Notification) {
        
        //若正在拖动进度，则忽略
        if self.controlView.dragType == .progress {
            return;
        }
        
        let st = player.time.intValue
        let rt = player.remainingTime?.intValue ?? -1
        print("时间变化:\(st) remaintiming: \(rt)")
        
        guard let totalTime = player.media?.length.intValue else {
            return
        }
        
//        printLog("总时长\(totalTime)")
        
        let pro = CGFloat(st)/CGFloat(totalTime)
        
        DispatchQueue.main.async {
            self.controlView.sliderView.value = Float(max(min(1.0, pro),0.0))
        }
        let currTime = TimeInterval(Float(st)/1000.0)
        let tt = TimeInterval(Float(totalTime)/1000.0)
        self.controlView.timeView.currTimeL.text = currTime.toHourMinSecond()
        self.controlView.timeView.totalTimeL.text = tt.toHourMinSecond()
    }
}


class BLVideoPlayerNoDataView: UIView {
    let moreBtn = UIButton()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.setupNoVideoUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupNoVideoUI() {
        let v = self
        v.backgroundColor = .black
        let logoView = ImageView.img("logo60").pin(.wh(60, 60))
        let textL = Label.font("30").color(ColorF)
        textL.text = "Please add media files"
        VStack(NERSpring, logoView,40,textL,NERSpring).embedIn(v).align(.center)
        
        let ig = UIImage.init(named: "list_w")// "home_list")
        moreBtn.pin(.wh(50, 50))
        moreBtn.img(ig).imageView?.pin(.wh(26, 24))
        moreBtn.setImage(ig?.withTintColor(ColorMain), for: .highlighted)
        moreBtn.addTo(v).makeCons { make in
            make.top.equal(10)
            make.right.equal(-10)
        }
    }
}
